package advanced.class04;

import java.util.LinkedList;

public class Test {

    public static int getComputeRes(String s){
        return value(s.toCharArray(),0)[0];
    }

    // 求解
    public static int[] value(char[] chars, int index) {
        // 创建辅助变量
        int pre = 0;
        LinkedList<String> que = new LinkedList<>();
        int[] bra = null;
        // 两种情况结束，一种是当前索引遍历结束，一种是当前字符为')'
        while(index < chars.length && chars[index] != ')') {
            if(chars[index] >= '0' && chars[index] <= '9'){
                pre = pre * 10 + chars[index++] - '0';
            }else if(chars[index] != '('){
                addNum(que,pre);
                que.addLast(String.valueOf(chars[index++]));
                pre = 0;  // pre添加之后，重置为0
            }else{  // 这种就是碰到左括号的情况
                bra = value(chars,index+1);
                pre = bra[0];
                index = bra[1] + 1;
            }
        }
        addNum(que,pre);
        return new int[]{caculate(que),index};
    }

    // 将但钱遍历到的数字添加到链表中
    private static void addNum(LinkedList<String> que, int num) {
        if(!que.isEmpty()){
            int cur = 0;
            // 从栈中减元素弹出
            String top = que.pollLast();
            if(top.equals("+") || top.equals("-")){
                // 放回去不操作
                que.addLast(top);
            }else{
                cur = Integer.valueOf(que.pollLast());
                num = top.equals("*") ? (cur * num) : (cur / num);
            }
        }
        que.addLast(String.valueOf(num));
    }

    // 给定指定的que,求计算结果，链表中只存在加减
    private static int caculate(LinkedList<String> que) {
        int res = 0;
        boolean add = true;
        String cur = null;
        int num = 0;
        while(!que.isEmpty()){
            cur = que.pollFirst();
            if(cur.equals("+")){
                add = true;
            }else if(cur.equals("-")){
                add = false;
            }else{
                num = Integer.valueOf(cur);
                res += add ? num : (-num);
            }
        }
        return res;
    }


    public static void main(String[] args) {
        String exp = "48*((70-65)-43)+8*1";
        System.out.println(getComputeRes(exp));

        exp = "4*(6+78)+53-9/2+45*8";
        System.out.println(getComputeRes(exp));

        exp = "10-5*3";
        System.out.println(getComputeRes(exp));

        exp = "-3*4";
        System.out.println(getComputeRes(exp));

        exp = "3+1*4";
        System.out.println(getComputeRes(exp));

    }

}
